package org.jeecg.modules.charge.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.SsoUtil;
import org.jeecg.common.util.StringUtils;
import org.jeecg.entity.charge.ChargeBills;
import org.jeecg.entity.charge.ChargeInvoice;
import org.jeecg.entity.charge.ChargeInvoiceRequest;
import org.jeecg.enums.InvoiceTypeEnum;
import org.jeecg.enums.charge.InvoiceStatusEnum;
import org.jeecg.modules.charge.entity.ChargeBillsOrder;
import org.jeecg.modules.charge.service.IChargeBillsOrderService;
import org.jeecg.modules.charge.service.IChargeBillsService;
import org.jeecg.modules.charge.service.IChargeInvoiceRequestService;
import org.jeecg.service.IFeignChargeService;
import org.jeecg.vo.charge.ChargeOrderReqVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @Description: 订单表
 * @Author: jeecg-boot
 * @Date: 2019-08-15
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "订单表")
@RestController
@RequestMapping("/b/charge/chargeBillsOrder")
public class ChargeBillsOrderController {
    @Autowired
    private IChargeBillsOrderService chargeBillsOrderService;

    @Autowired
    private IChargeBillsService chargeBillsService;

    @Autowired
    private IChargeInvoiceRequestService chargeInvoiceRequestService;
    @Autowired
    private IFeignChargeService feignChargeService;

    /**
     * 分页列表查询
     *
     * @param chargeBillsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "订单表-分页列表查询")
    @ApiOperation(value = "订单表-分页列表查询", notes = "订单表-分页列表查询")
    @GetMapping(value = "/lists")
    public Result<IPage<ChargeBillsOrder>> queryPageLists(ChargeBillsOrder chargeBillsOrder,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        Result<IPage<ChargeBillsOrder>> result = new Result<IPage<ChargeBillsOrder>>();
        QueryWrapper<ChargeBillsOrder> queryWrapper = QueryGenerator.initQueryWrapper(chargeBillsOrder, req.getParameterMap());
        Page<ChargeBillsOrder> page = new Page<ChargeBillsOrder>(pageNo, pageSize);
        IPage<ChargeBillsOrder> pageList = chargeBillsOrderService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    @AutoLog(value = "订单表-分页列表查询")
    @ApiOperation(value = "订单表-分页列表查询", notes = "订单表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<ChargeBillsOrder>> list(ChargeBillsOrder chargeBillsOrder,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        return null;
    }

    /**
     * 自定义分页查询
     *
     * @param chargeBillsOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/listByProject", method = RequestMethod.GET)
    public Result<Page<ChargeBillsOrder>> listByProject(ChargeBillsOrder chargeBillsOrder,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<Page<ChargeBillsOrder>> result = new Result<Page<ChargeBillsOrder>>();
        try {
             if (chargeBillsOrder.getProjectId() != null) {
                  String[] split = chargeBillsOrder.getProjectId().split(",");
                  chargeBillsOrder.setProjectIds(split);
             }
             Page<ChargeBillsOrder> page = new Page<ChargeBillsOrder>(pageNo, pageSize);
             List<ChargeBillsOrder> list = chargeBillsOrderService.listByProject(page,chargeBillsOrder);
//             if (list.size() > 0){
//                 for (ChargeBillsOrder order : list){
//                     if(StringUtils.isBlank(order.getBillids())){
//                         order.setFeeItemName(chargeBillsOrderService.getFeeNameByOrderId(order.getId(),order.getRefundStatus(),1));
//                     } else {
//                         order.setFeeItemName(chargeBillsOrderService.getFeeNameByOrderId(order.getId(),order.getRefundStatus(),0));
//                     }
//                 }
//             }
             page.setRecords(list);
             result.setSuccess(true);
             result.setResult(page);
           } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
         }
        return result;
    }

    @AutoLog(value = "充值订单-退款")
    @ApiOperation(value="充值订单-退款", notes="充值订单-退款")
    @GetMapping(value = "/refundCharge")
    public Result<ChargeBillsOrder> refundCharge(@RequestParam(name="orderId",required=true) String orderId) {
        try {
            return chargeBillsOrderService.refundCharge(orderId);
        } catch (RuntimeException re){
            return Result.error(re.getMessage());
        }
    }

    @AutoLog(value = "物业费充值发票")
    @ApiOperation(value="物业费充值发票", notes="物业费充值发票")
    @RequestMapping(value = "/getInvoiceList")
    public Result<List<ChargeInvoiceRequest>> getInvoiceList(@RequestParam(name = "orderNum", required = true) String orderNum){
        try {
            List<ChargeInvoiceRequest> list = chargeBillsOrderService.invoiceRequestListBySn(orderNum);
            return Result.ok(list);
        }catch (Exception ex){
            log.error("操作失败", ex.getMessage());
            return Result.error("操作失败！");
        }
    }

    @AutoLog(value = "发票红冲")
    @ApiOperation(value="发票红冲", notes="发票红冲")
    @RequestMapping(value = "/redInvoice")
    public Result redInvoice(@RequestParam(name = "lsh", required = true) String lsh){
        try {
            ChargeInvoiceRequest req = chargeBillsOrderService.invoiceRequestByFpqqlsh(lsh);
            boolean b = feignChargeService.openRed(JSON.toJSONString(req), req.getTenantId());
            if (b){
                return Result.ok("红冲成功");
            }
            return Result.ok("红冲失败");
        }catch (Exception ex) {
            log.error("操作失败", ex.getMessage());
            return Result.error("红冲失败！");
        }
    }

    @AutoLog(value = "发票补开")
    @ApiOperation(value="发票补开", notes="发票补开")
    @RequestMapping(value = "/blueInvoice")
    public Result blueInvoice(@RequestBody ChargeBillsOrder billsOrder){
        try {
            ChargeBillsOrder order = chargeBillsOrderService.getBillOrderBySn(billsOrder.getSn());
            if (order == null) return Result.error("订单在系统中不存在!");
            ChargeInvoiceRequest invoiceRequest = chargeInvoiceRequestService.getInfoByOrder(order.getSn());
            if (invoiceRequest != null && InvoiceStatusEnum.INVOICE_STATUS_SUCCESS.getCode().equals(invoiceRequest.getInvoiceStatus())){
                Result.error("当前订单已开票,请勿重复开票!");
            }
            order.setInvoiceType(InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode());
            order.setInvoiceName(billsOrder.getInvoiceName());
            order.setInvoiceEmail(billsOrder.getInvoiceEmail());
            order.setInvoiceEin(billsOrder.getInvoiceEin());
            Result result = chargeBillsOrderService.chargeBlueInvoice(order);
            return result;
        }catch (Exception ex) {
            log.error("操作失败:{}", ex);
            return Result.error("补开失败！");
        }
    }


    @AutoLog(value = "账单周期查询")
    @ApiOperation(value = "账单周期查询", notes = "账单周期查询")
    @GetMapping(value = "/listById")
    public Result<String> listById(ChargeBillsOrder chargeBillsOrder){
        Result<String> result = new Result<>();
        if (chargeBillsOrder.getBillids() != null){
            String billIds =(String) chargeBillsOrder.getBillids();
            String[] ids = billIds.split(",");
            List<ChargeBills> chargeBills = chargeBillsService.listById(ids);
            StringBuilder stringBuilder = new StringBuilder();
            for (int i = 0; i < chargeBills.size(); i++) {
                stringBuilder.append(chargeBills.get(i).getZjCny());
                if (i!= chargeBills.size()-1){
                    stringBuilder.append(",");
                }
            }
            result.setSuccess(true);
            result.setResult(stringBuilder.toString());
            return  result;
        }else {
            return  null;
        }

    }
    @AutoLog(value = "开票状态查询")
    @ApiOperation(value = "开票状态查询", notes = "开票状态查询")
    @GetMapping(value = "/listOrder")
    public Result<String> listOrder(ChargeBillsOrder chargeBillsOrder){
        String sn = chargeBillsOrder.getSn();
        Result<String> result = new Result<>();
        List<ChargeInvoiceRequest> chargeInvoiceRequest = chargeInvoiceRequestService.listBySn(sn);
        String status = "";
        boolean invoiceSuccess = false;
        for (ChargeInvoiceRequest temp : chargeInvoiceRequest){
            if (StringUtils.isNotEmpty(temp.getInvoiceStatus()) && temp.getInvoiceStatus().equals("1")){
                invoiceSuccess = true;
            }else {
                invoiceSuccess = false;
                break;
            }

        }
        status = invoiceSuccess ? "1":"0";
        result.setSuccess(true);
        result.setResult(status);
        return  result;
    }

    @ApiOperation(value="物业费-线下收费", notes="物业费-线下收费")
    @RequestMapping(value = "/unLineCharge")
    public Result<ChargeBillsOrder> unLineCharge(@RequestBody ChargeOrderReqVo reqVo) {
        log.info("日常线下收费接受参数:{}",reqVo);
        if (StringUtils.isBlank(reqVo.getRoomId())){
            return Result.error("请选择支付对应的房间!");
        }
        Result<ChargeBillsOrder> result = chargeBillsOrderService.unLineCharge(reqVo);
        if (result.isSuccess()){
            chargeBillsOrderService.autoBills(reqVo);//自动生成账单
            if (InvoiceTypeEnum.INVOICE_TYPE_ELE.getCode().equals(reqVo.getInvoiceType())) {//开票
               Result invoiceRes =  chargeBillsOrderService.chargeBlueInvoice(result.getResult());
               return Result.ok("收费成功!" + invoiceRes.getMessage());
            }
        }
        return result;
    }

    @AutoLog(value = "物业费-扫码枪收费")
    @ApiOperation(value="物业费-扫码枪收费", notes="物业费-扫码枪收费")
    @PostMapping(value = "/unLineQRCodeCharge")
    public Result<ChargeInvoice> unLineQRCodeCharge(@RequestBody ChargeOrderReqVo reqVo) {
        Result<ChargeInvoice> result = null;
        try {
            result = chargeBillsOrderService.unLineQRCodeCharge(reqVo);
            return result;
        }catch (Exception ex){
//            ex.printStackTrace();
            return Result.error("银行下单失败！");
        }
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(ChargeBillsOrder chargeBillsOrder) {
        // Step.1 组装查询条件
        LoginUser user = SsoUtil.getLoginUser();
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        if (chargeBillsOrder.getProjectId() != null) {
            String[] split = chargeBillsOrder.getProjectId().split(",");
            chargeBillsOrder.setProjectIds(split);
        }
        List<ChargeBillsOrder> list = chargeBillsOrderService.listByProject(null,chargeBillsOrder);
//        if (list.size() > 0){
//            for (ChargeBillsOrder order : list){
//                if(StringUtils.isBlank(order.getBillids())){
//                    order.setFeeItemName(chargeBillsOrderService.getFeeNameByOrderId(order.getId(),order.getRefundStatus(),1));
//                } else {
//                    order.setFeeItemName(chargeBillsOrderService.getFeeNameByOrderId(order.getId(),order.getRefundStatus(),0));
//                }
//            }
//        }
        //导出文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "缴费订单明细");
        mv.addObject(NormalExcelConstants.CLASS, ChargeBillsOrder.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("缴费订单明细", "导出人:" + user.getRealname(), "导出信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, list);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ChargeBillsOrder> listChargeBillsOrders = ExcelImportUtil.importExcel(file.getInputStream(), ChargeBillsOrder.class, params);
                chargeBillsOrderService.saveBatch(listChargeBillsOrders);
                return Result.ok("文件导入成功！数据行数:" + listChargeBillsOrders.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }

}
